package web.Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        System.out.println("doFilter");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        HttpServletRequest req = (HttpServletRequest) request;
        //如果是登录注册有关的要放
        String[] urls={"/auto/login","/auto/register","/auto/checkName","/auto/checkCode","/login.html","/register.html","/js/"};
        String url= req.getRequestURI();
        for(String s:urls){
            if(url.contains(s)){
                chain.doFilter(request, response);
                return;
            }
        }

        HttpSession session=req.getSession();
        Object user =  session.getAttribute("userDTO");
        System.out.println(user);
        //检查session里面有没有东西
        if (user != null) {
            //有，去吧
            System.out.println("放行");
            chain.doFilter(request, response);
        }else{
            //没有，登录去
            System.out.println("拦截");
            //req.getRequestDispatcher( "/login.html").forward(req,response);这个不行
            ((HttpServletResponse) response).sendRedirect(req.getContextPath() + "/login.html");
        }

    }








    @Override
    public void init(FilterConfig config) throws ServletException {
    }
    @Override
    public void destroy() {
    }


}
